<template>
  <div class="login-container">
    <!-- 左侧品牌展示区 -->
    <div class="login-brand">
      <div class="brand-content">
        <h1>旅行预约系统</h1>
        <p class="brand-subtitle">一站式旅行服务管理平台</p>
        <div class="brand-features">
          <div class="feature-item">
            <div class="feature-icon">✈️</div>
            <span>机票预订</span>
          </div>
          <div class="feature-item">
            <div class="feature-icon">🏨</div>
            <span>酒店预订</span>
          </div>
          <div class="feature-item">
            <div class="feature-icon">🚌</div>
            <span>巴士服务</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧登录表单区 -->
    <div class="login-form-section">
      <div class="login-form-wrapper">
        <div class="form-header">
          <h2>欢迎回来</h2>
          <p>请输入您的账号信息登录系统</p>
        </div>

        <el-form
            ref="loginFormRef"
            :model="formData"
            :rules="formRules"
            @submit.prevent="handleLogin"
            class="login-form"
            size="large"
        >
          <div class="form-item-group">
            <el-form-item prop="customerName" class="form-item">
              <template #label>
                <span class="form-label">用户名</span>
              </template>
              <el-input
                  v-model="formData.customerName"
                  placeholder="请输入用户名"
                  :prefix-icon="User"
                  clearable
              />
            </el-form-item>

            <el-form-item prop="customerId" class="form-item">
              <template #label>
                <span class="form-label">用户ID</span>
              </template>
              <el-input
                  v-model="formData.customerId"
                  placeholder="请输入用户ID"
                  :prefix-icon="Lock"
                  clearable
              />
            </el-form-item>
          </div>

          <div class="form-options">
            <el-form-item prop="rememberMe" class="remember-me-item">
              <el-checkbox v-model="formData.rememberMe">
                <span class="remember-me-label">记住我</span>
              </el-checkbox>
            </el-form-item>
          </div>

          <el-form-item class="submit-item">
            <el-button
                type="primary"
                native-type="submit"
                :loading="authStore.loading"
                class="login-btn"
                size="large"
            >
              {{ authStore.loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div v-if="errorMessage" class="error-message">
          <el-icon><Warning /></el-icon>
          {{ errorMessage }}
        </div>

        <div class="login-footer">
          <p>首次使用？系统将在需要时自动为您注册</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../stores/authStore.ts'
import { User, Lock, Warning } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

// 定义表单数据类型
interface LoginForm {
  customerName: string
  customerId: string
  rememberMe: boolean
}

// 使用Pinia store
const authStore = useAuthStore()
const router = useRouter()
const loginFormRef = ref<FormInstance>()

// 响应式数据
const formData = reactive<LoginForm>({
  customerName: '',
  customerId: '',
  rememberMe: false
})

const errorMessage = ref('')

// 表单校验规则
const formRules = reactive<FormRules<LoginForm>>({
  customerName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20之间', trigger: 'blur' },
  ],
  customerId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { min: 1,max:20, message: '用户ID不能为空', trigger: 'blur' },
  ]
})

// 登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return

  // 先进行表单验证
  const valid = await loginFormRef.value.validate().catch(() => false)
  if (!valid) return

  errorMessage.value = ''

  // 使用Pinia的action进行登录
  const result = await authStore.login(
      formData.customerName,
      formData.customerId,
      formData.rememberMe
  )

  if (result.success) {
    // 登录成功，跳转到主页
    router.push({ name: 'TravelReservation' })
  } else {
    errorMessage.value = result.error || '登录失败'
  }
}

// 重置表单验证
const resetFormValidation = () => {
  if (loginFormRef.value) {
    loginFormRef.value.clearValidate()
  }
}

// 组件挂载时检查是否有保存的用户信息
onMounted(() => {
  // 从localStorage获取保存的用户信息
  const savedCustomerName = localStorage.getItem('auth_customerName')
  const savedCustomerId = localStorage.getItem('auth_customerId')

  if (savedCustomerName) {
    formData.customerName = savedCustomerName
  }
  if (savedCustomerId) {
    formData.customerId = savedCustomerId
  }
  formData.rememberMe = !!savedCustomerName

  // 监听表单数据变化，清除错误信息
  Object.keys(formData).forEach(key => {
    const reactiveKey = key as keyof LoginForm
    watch(() => formData[reactiveKey], () => {
      errorMessage.value = ''
      resetFormValidation()
    })
  })
})
</script>

<style scoped>
/* 保持原有的样式不变 */
.login-container {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-brand {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 2rem;
  color: white;
}

.brand-content {
  max-width: 400px;
  text-align: center;
}

.brand-content h1 {
  font-size: 2.5rem;
  font-weight: 700;
  margin-bottom: 1rem;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.brand-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-bottom: 3rem;
}

.brand-features {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  font-size: 1.1rem;
}

.feature-icon {
  font-size: 1.5rem;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
}

.login-form-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  padding: 2rem;
}

.login-form-wrapper {
  width: 100%;
  max-width: 400px;
}

.form-header {
  text-align: center;
  margin-bottom: 2.5rem;
}

.form-header h2 {
  font-size: 2rem;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 0.5rem;
}

.form-header p {
  color: #666;
  font-size: 0.95rem;
}

.login-form {
  margin-bottom: 2rem;
}

.form-item-group {
  margin-bottom: 1.5rem;
}

.form-item {
  margin-bottom: 1.5rem;
}

:deep(.form-item .el-form-item) {
  margin-bottom: 0;
}

:deep(.form-item .el-form-item__content) {
  display: flex;
  flex-direction: column;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #374151;
  font-size: 0.95rem;
}

:deep(.form-item .el-input) {
  width: 100%;
}

:deep(.form-item .el-input__wrapper) {
  border-radius: 8px;
  padding: 0 12px;
  height: 48px;
  box-sizing: border-box;
}

:deep(.form-item .el-input__inner) {
  height: 46px;
  line-height: 46px;
}

:deep(.form-item .el-form-item__error) {
  margin-top: 4px;
  font-size: 0.8rem;
}

:deep(.form-item .el-input) {
  min-height: 48px;
}

:deep(.form-item .el-input__wrapper) {
  min-height: 48px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.remember-me-item {
  margin-bottom: 0 !important;
}

:deep(.remember-me-item .el-form-item__content) {
  line-height: 1;
}

.remember-me-label {
  font-size: 0.9rem;
  color: #374151;
}

:deep(.remember-me-item .el-checkbox) {
  margin-right: 0;
}

.submit-item {
  margin-bottom: 0;
}

:deep(.submit-item .el-form-item__content) {
  justify-content: center;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 1rem;
  font-weight: 600;
  border-radius: 8px;
  margin-top: 0.5rem;
}

:deep(.el-button) {
  transition: all 0.2s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
}

.error-message {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem;
  background-color: #fef2f2;
  color: #f56c6c;
  border: 1px solid #fde2e2;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  font-size: 0.9rem;
}

.login-footer {
  text-align: center;
  padding-top: 1.5rem;
  border-top: 1px solid #e5e7eb;
}

.login-footer p {
  color: #6b7280;
  font-size: 0.9rem;
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }

  .login-brand {
    padding: 1.5rem;
  }

  .brand-content h1 {
    font-size: 2rem;
  }
}

@media (max-width: 480px) {
  .login-form-section {
    padding: 1rem;
  }

  .form-header h2 {
    font-size: 1.75rem;
  }

  :deep(.form-item .el-input__wrapper) {
    height: 44px;
  }

  :deep(.form-item .el-input__inner) {
    height: 42px;
    line-height: 42px;
  }

  .login-btn {
    height: 44px;
  }
}
</style>